package com.mflex.flexwi;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.collection.SimpleArrayMap;

import com.dou361.dialogui.DialogUIUtils;
import com.mflex.flexwi.util.PackageUtils;
import com.mflex.flexwi.util.WebServiceUtil;
import com.rosefinches.smiledialog.SmileDialog;
import com.rosefinches.smiledialog.SmileDialogBuilder;
import com.rosefinches.smiledialog.enums.SmileDialogType;

import org.apache.commons.lang3.StringUtils;

public class LoginActivity extends BaseActivity {
    private LinearLayout linearLayout1;
    private LinearLayout loginTop;
    private LinearLayout loginTitle;
    private TextView txtTtitle;
    private LinearLayout loginLogin;
    private LinearLayout linearLayout6;
    private TextView textView1;
    private EditText txtUser;
    private LinearLayout linearLayout7;
    private TextView textView2;
    private EditText txtPwd;
    private Button btnLogin;
    private Button btnConfig;
    private LinearLayout linearLayout14;
    private TextView txtMsg;
    private TextView txtVersion;
    private TextView txtCurrentServer;
    private LinearLayout loginConfig;
    private LinearLayout linearLayout9;
    private TextView textView3;
    private EditText txtServerName;
    private LinearLayout linearLayout10;
    private TextView textView4;
    private EditText txtServerPort;
    private LinearLayout linearLayout11;
    private TextView textView5;
    private EditText txtServerFloder;
    private LinearLayout linearLayout12;
    private TextView textView6;
    private EditText txtServerPage;
    private Button btnSaveConfig;
    private Button btnCancel;

    private static String url;
    private static String pdfUrl;
    private String config = "messmtuat01.mflex.com.cn,80,WIWS,WebService.asmx";
    private int cc = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        DialogUIUtils.init(this);

//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
//        float scaledDensity = this.getResources().getDisplayMetrics().scaledDensity;
//        float density = this.getResources().getDisplayMetrics().density;
//        float xdpi = this.getResources().getDisplayMetrics().xdpi;
//        float ydpi = this.getResources().getDisplayMetrics().ydpi;
//        int width = this.getResources().getDisplayMetrics().widthPixels;
//        int height = this.getResources().getDisplayMetrics().heightPixels;
//
//        // 这样可以计算屏幕的物理尺寸
//        float width2 = (width / xdpi)*(width / xdpi);
//        float height2 = (height / ydpi)*(width / xdpi);
//
//        float aa = (float) Math.sqrt(width2+height2);
//        SmileDialog dialog1 = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
//                .setContentText(String.valueOf(aa))
//                .setTitleText("错误提示")
//                .build();
//        dialog1.show();

        linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
        loginTop = (LinearLayout) findViewById(R.id.loginTop);
        loginTitle = (LinearLayout) findViewById(R.id.loginTitle);
        txtTtitle = (TextView) findViewById(R.id.txtTtitle);
        loginLogin = (LinearLayout) findViewById(R.id.loginLogin);
        linearLayout6 = (LinearLayout) findViewById(R.id.linearLayout6);
        textView1 = (TextView) findViewById(R.id.textView1);
        txtUser = (EditText) findViewById(R.id.txtUser);
        linearLayout7 = (LinearLayout) findViewById(R.id.linearLayout7);
        textView2 = (TextView) findViewById(R.id.textView2);
        txtPwd = (EditText) findViewById(R.id.txtPwd);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnConfig = (Button) findViewById(R.id.btnConfig);
        linearLayout14 = (LinearLayout) findViewById(R.id.linearLayout14);
        txtMsg = (TextView) findViewById(R.id.txtMsg);
        txtVersion = (TextView) findViewById(R.id.txtVersion);
        txtCurrentServer = (TextView) findViewById(R.id.txtCurrentServer);
        loginConfig = (LinearLayout) findViewById(R.id.loginConfig);
        linearLayout9 = (LinearLayout) findViewById(R.id.linearLayout9);
        textView3 = (TextView) findViewById(R.id.textView3);
        txtServerName = (EditText) findViewById(R.id.txtServerName);
        linearLayout10 = (LinearLayout) findViewById(R.id.linearLayout10);
        textView4 = (TextView) findViewById(R.id.textView4);
        txtServerPort = (EditText) findViewById(R.id.txtServerPort);
        linearLayout11 = (LinearLayout) findViewById(R.id.linearLayout11);
        textView5 = (TextView) findViewById(R.id.textView5);
        txtServerFloder = (EditText) findViewById(R.id.txtServerFloder);
        linearLayout12 = (LinearLayout) findViewById(R.id.linearLayout12);
        textView6 = (TextView) findViewById(R.id.textView6);
        txtServerPage = (EditText) findViewById(R.id.txtServerPage);
        btnSaveConfig = (Button) findViewById(R.id.btnSaveConfig);
        btnCancel = (Button) findViewById(R.id.btnCancel);

        //隐藏配置项
        loginLogin.setVisibility(View.VISIBLE);
        loginConfig.setVisibility(View.GONE);
        btnConfig.setVisibility(View.GONE);

        //设置焦点
        txtUser.setFocusable(true);
        txtUser.setFocusableInTouchMode(true);
        txtUser.requestFocus();

        //        txtUser.setFocusable(false);
//
//        txtUser.setFocusableInTouchMode(false);
//        txtUser.setInputType(InputType.TYPE_NULL);

//        //获取服务器选择
//        RadioButton radioButton = (RadioButton) findViewById(rgOrientation.getCheckedRadioButtonId());
//        serverFlag = radioButton.getText().toString();

        txtTtitle.setText(PackageUtils.getAppName(this));
        txtVersion.setText("Version " + PackageUtils.getVersionName(this));

//        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
//        SmileDialog dialog1 = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
//                .setContentText(mDisplayMetrics.widthPixels+"____"+mDisplayMetrics.heightPixels+"____"+mDisplayMetrics.density+"___"+mDisplayMetrics.densityDpi+"--")
//                .setTitleText("错误提示")
//                .build();
//        dialog1.show();
        if (!checkIP()) {
            SmileDialog dialog = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
                    .setContentText("Not connected to MES network or production network!")
                    .setTitleText("Error message")
                    .build();
            dialog.show();
        } else {
            //获取webservice服务器配置
            SharedPreferences mShare = getSharedPreferences("FlexWIDocumentConfig", Context.MODE_PRIVATE);
//            String serverName = mShare.getString("ServerName", StringUtils.EMPTY);
//            String serverPort = mShare.getString("ServerPort", StringUtils.EMPTY);
//            String serverFloder = mShare.getString("ServerFloder", StringUtils.EMPTY);
//            String serverPage = mShare.getString("ServerPage", StringUtils.EMPTY);
            String[] configArrary;
            //初始化时未配置服务器信息
//            if (StringUtils.isEmpty(serverName)) {
//                String ip = getLocalIpAddress();
//                if (ip.startsWith("172.16") || ip.startsWith("10.2") || ip.startsWith("10.3")) {
//                    //红庄厂区
//                    config = "messmtpda.mflex.com.cn,80,WIWS,WebService.asmx";
//                }
//                else if(ip.startsWith("10.101")){
//                    //郭巷厂区
//                    config = "mfcmesflexpda.mflex.com.cn,80,WIWS,WebService.asmx";
//                }
//                else if (ip.startsWith("172.18") || ip.startsWith("10.13")) {
                    //盐城厂区
//                    config = "mycmesflexpda.mflex.com.cn,80,WIWS,WebService.asmx";
            //泰国
            config = BuildConfig.API_HOST;
//                }
                SharedPreferences.Editor editor = mShare.edit();
                configArrary = config.split(",");
                editor.putString("ServerName", configArrary[0]);
                editor.putString("ServerPort", configArrary[1]);
                editor.putString("ServerFloder", configArrary[2]);
                editor.putString("ServerPage", configArrary[3]);
                txtServerName.setText(configArrary[0]);
                txtServerPort.setText(configArrary[1]);
                txtServerFloder.setText(configArrary[2]);
                txtServerPage.setText(configArrary[3]);
                txtCurrentServer.setText(configArrary[0]);
                url = "http://" + configArrary[0] + ":" + configArrary[1] + "/" + configArrary[2] + "/" + configArrary[3];

                pdfUrl = "http://" + configArrary[0] + ":" + configArrary[1] + "/" + configArrary[2] + "/Default.aspx";

//            } else {
//
//                txtCurrentServer.setText(serverName);
//
//                txtServerName.setText(serverName);
//                txtServerPort.setText(serverPort);
//                txtServerFloder.setText(serverFloder);
//                txtServerPage.setText(serverPage);
//
//                url = "http://" + serverName + ":" + serverPort + "/" + serverFloder + "/" + serverPage;
//                pdfUrl = "http://" + serverName + ":" + serverPort + "/" + serverFloder + "/Default.aspx";
//            }

        }
        //设置监听
        setListener();

    }

    private void setListener() {
        //登录按钮监听
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(txtUser.getText())) {
                    SmileDialog dialog = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
                            .setContentText("MES account is empty!")
                            .setTitleText("Error message")
                            .build();
                    dialog.show();
                    return;
                }
                if (StringUtils.isEmpty(txtPwd.getText())) {
                    SmileDialog dialog = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
                            .setContentText("MES password is empty!")
                            .setTitleText("Error message")
                            .build();
                    dialog.show();
                    return;
                }
//                RadioButton radioButton = (RadioButton) findViewById(rgOrientation.getCheckedRadioButtonId());
//                String radioText = radioButton.getText().toString();

                request();

            }
        });

        //配置按钮监听
        btnConfig.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                RadioButton radioButton = (RadioButton) findViewById(rgOrientation.getCheckedRadioButtonId());
//                String radioText = radioButton.getText().toString();

                loginLogin.setVisibility(View.GONE);
                loginConfig.setVisibility(View.VISIBLE);
            }
        });

        //保存按钮监听
//        btnSaveConfig.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!checkFormContext()) {
//                    return;
//                }
//
//                //获取webservice服务器配置
//                SharedPreferences mShare = getSharedPreferences("FlexWIDocumentConfig", Context.MODE_PRIVATE);
//                SharedPreferences.Editor editor = mShare.edit();
//                editor.putString("ServerName", txtServerName.getText().toString());
//                editor.putString("ServerPort", txtServerPort.getText().toString());
//                editor.putString("ServerFloder", txtServerFloder.getText().toString());
//                editor.putString("ServerPage", txtServerPage.getText().toString());
//                editor.commit();
//
//                url = "http://" + txtServerName.getText().toString() + ":" + txtServerPort.getText().toString() + "/" + txtServerFloder.getText().toString() + "/" + txtServerPage.getText().toString();
//                pdfUrl = "http://" + txtServerName.getText().toString() + ":" + txtServerPort.getText().toString() + "/" + txtServerFloder.getText().toString() + "/Default.aspx";
//
////                txtServerName.setText(txtServerName.getText().toString());
////                txtServerPort.setText(txtServerPort.getText().toString());
////                txtServerFloder.setText(txtServerFloder.getText().toString());
////                txtServerPage.setText(txtServerPage.getText().toString());
//                txtCurrentServer.setText(txtServerName.getText().toString());
//
//                loginLogin.setVisibility(View.VISIBLE);
//                loginConfig.setVisibility(View.GONE);
//                btnConfig.setVisibility(View.GONE);
//                DialogUIUtils.showToastLong("配置成功");
//            }
//        });

        //取消按钮监听
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginLogin.setVisibility(View.VISIBLE);
                loginConfig.setVisibility(View.GONE);
                btnConfig.setVisibility(View.GONE);

            }
        });

        /**
         * 打开服务器配置按钮
         * @param view
         */
        txtCurrentServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cc++;
                if (cc == 6) {
                    btnConfig.setVisibility(View.VISIBLE);
                    cc = 0;
                    DialogUIUtils.showToast("Configure service activation");
                }
            }
        });
    }

    /**
     * 检查配置信息
     *
     * @return
     */
    private boolean checkFormContext() {
        if (StringUtils.isEmpty(txtServerName.getText().toString())) {
            SmileDialog dialog = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
                    .setContentText("ServerName is empty!")
                    .setTitleText("Error message")
                    .build();
            return false;
        }

        if (StringUtils.isEmpty(txtServerPort.getText().toString())) {
            SmileDialog dialog = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
                    .setContentText("ServerPort is empty!")
                    .setTitleText("Error message")
                    .build();
            return false;
        }

        if (StringUtils.isEmpty(txtServerFloder.getText().toString())) {
            SmileDialog dialog = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
                    .setContentText("ServerFloder is empty!")
                    .setTitleText("Error message")
                    .build();
            return false;
        }

        if (StringUtils.isEmpty(txtServerPage.getText().toString())) {
            SmileDialog dialog = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
                    .setContentText("ServerPage is empty!")
                    .setTitleText("Error message")
                    .build();
            return false;
        }
        return true;
    }

    /**
     * 登录请求
     */
    private void request() {
        final Dialog bean = DialogUIUtils.showLoading(LoginActivity.this, "Logging in", false, false, false, false).show();
        SimpleArrayMap<String, Object> map = new SimpleArrayMap<>();
//        map.put("Result", new Object());
        map.put("Username", txtUser.getText().toString());
        map.put("Password", txtPwd.getText().toString());
        WebServiceUtil.call(url, "CanLogin", map, new WebServiceUtil.ResponseCallBack() {
            @Override
            public void onSuccess(Object result) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("userName", txtUser.getText().toString());
                intent.putExtra("userPassword", txtPwd.getText().toString());
                intent.putExtra("webServiceUrl", url);

                intent.putExtra("pdfUrl", pdfUrl);

                startActivity(intent);
                DialogUIUtils.dismiss(bean);
            }

            @Override
            public void onError(String e) {

                DialogUIUtils.dismiss(bean);
                SmileDialog dialog = new SmileDialogBuilder(LoginActivity.this, SmileDialogType.ERROR)
                        .setContentText(e)
                        .setTitleText("Error message")
                        .build();
                dialog.show();
            }
        });
    }

    /**
     * 检查IP
     *
     * @return
     */
    private boolean checkIP() {
        String ip = getLocalIpAddress();
        if (!StringUtils.isEmpty(ip)) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前ip地址
     *
     * @return
     */
    public String getLocalIpAddress() {
        String ipaddress = "";
        try {
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
            WifiInfo wifiInfo;
            wifiInfo = wifiManager.getConnectionInfo();
            int ip = wifiInfo.getIpAddress();
            ipaddress = intToIp(ip);
            if (!StringUtils.isEmpty(ipaddress)) {
                if (ipaddress.contains("192.168")) {
                    return ipaddress;
                }
                if (ipaddress.startsWith("192.") || ipaddress.startsWith("172.") || ipaddress.startsWith("10.")) {
                    return ipaddress;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 转换IP
     *
     * @param i
     * @return
     */
    private String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }
}
